package net.kleinhenz.droidshop;

import java.io.IOException;
import java.net.URL;

import net.kleinhenz.droidshop.model.Motd;
import net.kleinhenz.droidshop.xml.DroidShopXMLException;
import net.kleinhenz.droidshop.xml.MotdXMLHandler;
import android.content.Context;
import android.os.Handler;
import android.util.Log;

public class MotdThread extends Thread
{
	// TODO: canocalize values
	public static final int OK = 1;
	public static final int ERROR_PARSING = -3;
	public static final int ERROR_RETRIEVING = -4;
	
	private Context context = null;
	private Handler handler = null;
	private Motd motd = null;
	
	public MotdThread(Context context, Handler handler) 
	{
		super();
		this.context = context;
		this.handler = handler;
	}
	
	public Motd getResult()
	{
		return motd;
	}
	
	@Override
	public void run()
	{
		MotdXMLHandler xmlHandler = new MotdXMLHandler();
		try 
		{
			Log.i("DroidShop", "Getting motd.");
			motd = xmlHandler.readDroidShopMotdXML(new URL(context.getResources().getString(R.string.motd_url)));
			handler.sendEmptyMessage(OK);
		} 
		catch (DroidShopXMLException e) 
		{
			Log.e("DroidShop", "Error while parsing server result XML: " + e.getMessage());			
			handler.sendEmptyMessage(ERROR_PARSING);
		} 
		catch (IOException e) 
		{
			Log.e("DroidShop", "Error while retrieving server result XML: " + e.getMessage());
			handler.sendEmptyMessage(ERROR_RETRIEVING);
		}		
	}
}
